package com.jie.langlangmall.security.component;

import cn.hutool.json.JSONUtil;
import com.jie.langlangmall.common.api.CommonResult;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import java.io.IOException;

/**
 * @Author Jie
 * @Date 2024/11/21 20:52
 * @Email 3217998214@qq.com
 * @Description 自定义未登录或者token失效时的返回结果
 */
public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        response.setHeader("Access-Control-Allow-Origin", "*"); // 设置跨域
        response.setHeader("Cache-Control", "no-cache"); // 防止浏览器缓存
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        response.getWriter().println(JSONUtil.parse(CommonResult.unauthorized(authException.getMessage()))); // 返回未登录
        response.getWriter().flush();
    }
}
